package com.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * jdbc Connection 详解
 */
public class Jdbc2_Connection {
    public static void main(String[] args) throws Exception {
        // 1 . 注册驱动
        //Class.forName("com.mysql.jdbc.Driver");


        // 2. 获取连接
        String url = "jdbc:mysql://127.0.0.1:3306/bd1?useSSL=false";
        String username = "root";
        String password = "1234";
        Connection connection = DriverManager.getConnection(url, username, password);

        //3. 定义sql
        String sql1 = "update stu set age = 50 where id = 1";

        String sql2 = "update stu set age = 60 where id = 2";
        Statement statement = null;
        int n2  = 0;

        try {
            //开启事务
            connection.setAutoCommit(false);

            //4. 获取执行sql的对象Statement
            statement = connection.createStatement();

            //5. 执行sql
            int n1  = statement.executeUpdate(sql1);

            //6. 处理结果
            System.out.println(n1);
            //int n = 3/0;//出现异常 捕捉后会rollback

            //5. 执行sql
            n2 = statement.executeUpdate(sql2);

            //没有异常直接提交
            connection.commit();
        } catch (Exception e) {
            connection.rollback();
            e.printStackTrace();
        }

        //6. 处理结果
        System.out.println(n2);


        //7 .释放资源
        statement.close();
        connection.close();

    }
}
